package com.example.springboot3demo.google.oauth;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.xkcoding.http.config.HttpConfig;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.scope.AuthGoogleScope;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGoogleRequest;
import me.zhyd.oauth.utils.AuthScopeUtils;

import java.net.InetSocketAddress;
import java.net.Proxy;

@Slf4j
public class OAuthGoogleClient {
    private final AuthGoogleRequest authGoogleRequest;

    public OAuthGoogleClient(String clientId,
                             String clientSecret,
                             String redirectUri,
                             Boolean httpClientProxyEnable,
                             String httpClientProxyHost,
                             Integer httpClientProxyPort) {
        AuthConfig config = AuthConfig.builder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .redirectUri(redirectUri)
                .scopes(CollectionUtil.addAllIfNotContains(AuthScopeUtils.getDefaultScopes(AuthGoogleScope.values()), AuthGoogleScope.getCalendarScopes()))
                .build();
        if (httpClientProxyEnable) {
            Proxy clientProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpClientProxyHost, httpClientProxyPort));
            config.setHttpConfig(HttpConfig.builder().timeout(15000).proxy(clientProxy).build());
        }
        authGoogleRequest = new AuthGoogleRequest(config);

    }

    /**
     * 获取授权登录 Google OAuth 链接
     *
     * @param state 会话参数，用户授权后会在 Callback 中返回
     * @return 授权登录链接
     */
    public String requestAuthorizeURL(String state) {
        log.info("[Google OAuth] => Request  Authorize URL: {}", state);
        String authorizeURL = this.authGoogleRequest.authorize(state);
         log.info("[Google OAuth] => Response Authorize URL: {}", authorizeURL);
        return authorizeURL;
    }

    /**
     * Google OAuth 授权登录
     *
     * @param authCallback 回调参数
     * @return Google 用户信息
     */
    public AuthUser requestAuthorizeLogin(AuthCallback authCallback) {
        log.info("[Google OAuth] => Request  Authorize Login: {}", JSONUtil.toJsonStr(authCallback));
        AuthResponse response = this.authGoogleRequest.login(authCallback);
        log.info("[Google OAuth] => Response Authorize Login: {}", JSONUtil.toJsonStr(response));
        return (AuthUser) response.getData();
    }
}
